import { View } from "@tarojs/components";
import { useRequest } from "ahooks";
import React, { useState } from "react";
import { getList } from "../../api";
import { SearchInput } from "../../components";
import { RecoData } from "../index/models";
import { HotSearchBar } from "./components/HotSearchBar";
import { HotSearchList } from "./components/HotSearchList";
import "./index.scss";

const SearchBar = () => {
  const [keywords, setKeyWord] = useState<string>("");
  const [data, setData] = useState<RecoData[]>([]);
  const { run } = useRequest(getList, {
    manual: true,
    onSuccess: (res) => {
      setData(res);
    },
  });

  const handleOnChange = (e: any) => {
    setKeyWord(e.detail.value);
    if (!e.detail.value) {
      setData([]);
      return;
    }
  };

  const handleOnSelect = (value: string) => {
    run(value);
    setKeyWord(value);
  };

  const handleConfirm = (e: any) => {
    run(e.target.value);
  };

  return (
    <>
      <View className="search-container">
        <SearchInput
          confirmType="search"
          name="Search"
          onInput={handleOnChange}
          placeholder="搜一下您感兴趣的内容..."
          value={keywords}
          onConfirm={handleConfirm}
        />
        <View className="hot-container">
          {data.length ? (
            <HotSearchList data={data} />
          ) : (
            <HotSearchBar onSelect={handleOnSelect} />
          )}
        </View>
      </View>
    </>
  );
};

export default SearchBar;
